package com.cmrx.model.service.impl;

import com.cmrx.model.dao.CommonPictureDao;
import com.cmrx.model.dao.PictureThumbnailDao;
import com.cmrx.model.entity.CommonPicture;
import com.cmrx.model.entity.CommonPictureThumbnail;
import com.cmrx.model.entity.User;
import com.cmrx.model.service.CommonPictureServer;
import com.cmrx.model.util.Html2ImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service
@Transactional
public class CommonPictureServerImpl implements CommonPictureServer {
    @Autowired
    private CommonPictureDao commonPictureDao;

    @Autowired
    private PictureThumbnailDao pictureThumbnailDao;

    //添加图片，同时添加缩略图
    @Override
    public String AddPicture(User user, CommonPicture commonPicture) {
        /***********************图片表*************************/
        String pictureid = UUID.randomUUID().toString().replaceAll("-","");
        commonPicture.setId(pictureid);
        commonPicture.setCreateUser(user.getUserName());
        int count = commonPictureDao.addCommonPicture(commonPicture);

        /***********************缩略图表*************************/
        CommonPictureThumbnail pictureThumbnail = new CommonPictureThumbnail();
        pictureThumbnail.setId(UUID.randomUUID().toString().replaceAll("-",""));
        pictureThumbnail.setPictureId(pictureid);
        pictureThumbnail.setCreateUser(user.getUserName());
        pictureThumbnail.setContent(Html2ImageUtil.createThinPicture(commonPicture.getContent()));
        pictureThumbnailDao.addPictureThumbnail(pictureThumbnail);
        if(pictureid!=null && !"".equals(pictureid)) {
            return pictureid;
        }else{
            return "";
        }
    }


    //修改图片，同时修改缩略图
    @Override
    public boolean updatePicture(User user,String pictureId,byte[] content) {
        CommonPicture commonPicture = new CommonPicture();
        /***********************图片表*************************/
        commonPicture.setId(pictureId);
        commonPicture.setContent(content);
        commonPicture.setUpdateUser(user.getUserName());
        int result = commonPictureDao.updateById(commonPicture);
        /***********************缩略图表*************************/
        CommonPictureThumbnail pictureThumbnail = new CommonPictureThumbnail();
        pictureThumbnail.setPictureId(pictureId);
        pictureThumbnail.setUpdateUser(user.getUserName());
        pictureThumbnail.setContent(Html2ImageUtil.createThinPicture(content));
        int result1 = pictureThumbnailDao.updateById(pictureThumbnail);
        if(result>0 && result1>0){
            return true;
        }
        return false;
    }
}
